package LeetCode;

import java.util.Arrays;
import java.util.Scanner;

public class LC_016_3SumClosest {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while (sc.hasNext()) {
            String[] arr = sc.nextLine().trim().split("\\s+");
            int[] a = new int[arr.length];
            for (int i = 0; i < a.length; i++) {
                a[i] = Integer.parseInt(arr[i]);
            }
            int n = Integer.parseInt(sc.nextLine());
            System.out.println(threeSumClosest(a, n));
        }
        sc.close();
    }

    private static int threeSumClosest(int[] nums, int target) {
        if (nums == null || nums.length < 3)
            return 0;
        int min = Integer.MAX_VALUE;
        int val = 0;
        Arrays.sort(nums);
        for (int i = 0; i <= nums.length - 3; i++) {
            int low = i + 1;
            int high = nums.length - 1;
            while (low < high) {
                int sum = nums[i] + nums[low] + nums[high];
                if (Math.abs(target - sum) < min) {
                    min = Math.abs(target - sum);
                    val = sum;
                }
                if (target == sum) {
                    return val;
                } else if (target > sum) {
                    low++;
                } else {
                    high--;
                }
            }
        }
        return val;
    }
}